// challeng/pages/fplay/fplay.js
var app = getApp();
var answerTimer = null;
function createRandNum(n_type){
	var type = app.fRandomBy(1,2);
	var num1 = parseInt(RndNum(n_type));
	var num2 = parseInt(RndNum(n_type));
	var arr = [-2,-1,10,0,1,2,0,0,0,-10,10,-10];
	var num4 = app.fRandomBy(0,11);
	if(type==1){//减法
		var num3 = num1 - num2;
		num3 = num3 + parseInt(num4);
	}
	else{//加法
		var num3 = num1 + num2;
		num3 = num3 + parseInt(num4);
	}
	return [num1,num2,num3,type];
}
//获取指定位数的随机数
function RndNum(n){
	var rnd="";
	for(var i=0;i<n;i++)
	rnd+=Math.floor(Math.random()*10);
	return rnd;
}
Page({
	onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mem.id;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'&gType=3';
	  return {
		  title: sharedata.title,
	     // desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/addnums',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	if (res.data.code == 1) {
	                        	wx.showToast({
	                        		title:'次数\t+'+res.data.num,
	                        		icon:'none',
	                				mask:true,
	                				duration:1000
	                			});
		    	    	    } 
		    	        	else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	}
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
  data: {
	gametoken:'',
	openid:'',
  	mem:{},
  	total:0,
  	cur_num:0,
  	times:[],
  	g_nums:[],
	resettime:5,
	answerIng:false,
	problem:[],
	game_bg:'',
  	
  	beginCountDown: 5,//游戏开始--倒计时
    gamingStatus: 'notBegin',//游戏状态4个。notBegin未开始，running正在运行，fail挑战失败,success挑战成功
  },
  onLoad: function (options) {
	  var that = this;
	  wx.showLoading({title:'数据加载中...'});
	  app.sysInit(this,function(res){
		  app.getUserInfo(function (res) {
	      	var openid = res['openid'];
	      	//获取分享内容
	          app.getShareData(function(res){
	          	that.setData({shareData:res.data});
	          },openid,3);
	          
	      	that.setData({openid:openid});
	      	app.util.request({
			        url: 'entry/wxapp/fplay',
			        data: {
			          m: 'junsion_challeng',
			          t: 1,
			          openid:openid,
			          game:3,
			        },
			        success: function (res) {
			          wx.hideLoading();
			          if(res.data.code==0 || res.data.code==2){
			        	  var code = res.data.code;
			        	  wx.showModal({
			                  title:res.data.msg,
			                  showCancel:false,
			                  success: function(res) {
			                	  wx.showLoading({title:'数据加载中...'});
			                	  if(code==2)
			                		  var url = '../index/index?gobuy=1';
			                	  else var url = '../index/index';
			                	  wx.redirectTo({
			    	    			  url: url
			    	    		  })
			                  }
		                  });
			          }
			          else{
			        	  var problem = createRandNum(1);
			        	  that.setData({
			        		  game_bg:res.data.game_bg,
			        		  gametoken:res.data.gametoken,
			        		  mem:res.data.mem,
			        		  beginCountDown:res.data.down,
			        		  total:res.data.total,
			        		  times:res.data.times,
							  g_nums:res.data.g_nums,
			        		  resettime:res.data.times,
			        		  problem:problem,
			        		  answerIng:false,
			        	  });
			        	  if(parseInt(res.data.times[0])>0){
							  that.setData({
								  resettime:res.data.times[0],
							  });
						  }
						  else if(parseInt(res.data.times[1])>0){
							  that.setData({
								  resettime:res.data.times[1],
							  });
						  }
						  else if(parseInt(res.data.times[2])>0){
							  that.setData({
								  resettime:res.data.times[2],
							  });
						  }
						  else{
							  that.setData({
								  resettime:5,
							  });
						  }
			        	  that.beginCountDown(res.data.down);//游戏主入口
			          }
			        },
			    });
	      });
	  });
	  var music = wx.getStorageSync('music');
      that.setData({
		  music:music.music,
		  err_music:music.err_music,
	  });
	  
  },
  onReady: function () {
	  var that=this;
  	  this.audioCtx = wx.createAudioContext('myAudio')
      this.errAudio = wx.createAudioContext('errAudio')
      this.audioCtx.play()
  },
  goCheck:function(e){
	  var that = this;
  	  if(that.data.answerIng) return false;
  	  var dataset = e.currentTarget.dataset;
  	  var index = dataset.index;
  	  clearInterval(answerTimer);//用户选择答案之后就清除定时器，防止超时失败
  	  var problem = that.data.problem;
  	  if(parseInt(problem[3])==1)
  		  var num = parseInt(problem[0]) - parseInt(problem[1]);
  	  else 
  		  var num = parseInt(problem[0]) + parseInt(problem[1]);
  	  if((num==parseInt(problem[2]) && index==1) || (num!=parseInt(problem[2]) && index==0)){
  		  //回答正确
  		var cur_num = parseInt(that.data.cur_num);
  		cur_num++;
		if (cur_num == parseInt(that.data.total)) {
			app.checkReward(that,3,cur_num);//中奖了
			return false;
		}
		var n_type = 1;
		if(parseInt(that.data.g_nums[0])>=cur_num){
			var now_times=that.data.times[0];
			n_type = 1;
		}
		else if(parseInt(that.data.g_nums[1])>=cur_num){
			var now_times=that.data.times[1];
			n_type = 2;
		}
		else if(parseInt(that.data.g_nums[2])>=cur_num){
			var now_times=that.data.times[2];
			n_type = 3;
		}
		else{
			var now_times=5;
			n_type = 3;
		}
		var problem = createRandNum(n_type);
		that.timeCountDown(now_times);
		that.setData({problem:problem,answerIng:false,cur_num:cur_num});
  	  }
  	  else{
  		that.audioCtx.pause();
  		app.tzfail(that,3);//挑战失败
  	  }
  },
  onUnload: function(){
	  clearInterval(answerTimer);
  },
  timeCountDown:function(myTime){
  	var that=this;
  	if(answerTimer){
  		clearInterval(answerTimer);
  		that.setData({ resettime: myTime });
  	}
		answerTimer = setInterval(function () {
  		if(that.data.answerIng){
  			return false;
  		}
  		that.setData({ resettime: --myTime });
  		if (myTime <= 0) {
  			//时间到，失败
  			clearInterval(answerTimer);
  			//失败处理
  			that.audioCtx.pause()
  			app.tzfail(that,3);//挑战失败
  		}
  	}, 1000);
  	
  },
//游戏开始倒计时
  beginCountDown:function(countTime){
      var that=this;
      var timer = setInterval(function () {
          that.setData({ beginCountDown: --countTime });
          if (countTime <= 0) {
              clearInterval(timer);
              that.setData({
                  gamingStatus:'running'
              });
              that.timeCountDown(parseInt(that.data.resettime));//游戏主入口
          }
      }, 1000)
  }

})